package cn.seaboot.flake.jdbc;

import cn.seaboot.commons.core.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 将数据库查询结果封装为 map，并且将 key 值转为 camelCase。
 *
 * @author Mr.css
 * @version 2020-11-15 10:41
 */
public class CamelCaseResultSetExtractor<T> implements ResultSetExtractor<List<Map<String, Object>>> {

    @Override
    public List<Map<String, Object>> extractData(ResultSet resultSet) throws SQLException, DataAccessException {
        ResultSetMetaData metaData = resultSet.getMetaData();

        int len = metaData.getColumnCount() + 1;
        String[] names = new String[len];

        for (int i = 1; i < len; i++) {
            names[i] = StringUtils.underlineToCamel(metaData.getColumnName(i));
        }

        return JdbcUtils.toMap(resultSet, len, names);
    }
}
